using System;
using NDesk.Options;
using System.Data.SqlClient;

namespace Caramel.NDesk.Options
{
	public class SqlServerOptionSet : OptionSet
	{
		public SqlServerOptionSet()
			: this(null)
		{
		}

		public SqlServerOptionSet(string database)
		{
			this.Server = ".";
			this.Database = database;
			this.UseTrustedConnection = false;
			
			this.Add(
				"s|server=",
				"Instance of SQL Server to connect to.",
				value => this.Server = value
			);

			this.Add(
				"d|database=",
				"Database to create.",
				value => this.Database = value
			);

			this.Add(
				"e|useTrustedConnection",
				"Uses a trusted connection instead of requiring username and password.",
				value => this.UseTrustedConnection = value != null
			);

			this.Add(
				"u|user=",
				"User login id.",
				value => this.User = value
			);

			this.Add(
				"p|password=",
				"User-specified password.",
				value => this.Password = value
			);
		}

		public string Server { get; set; }

		public string Database { get; set; }

		public bool UseTrustedConnection { get; set; }

		public string User { get; set; }

		public string Password { get; set; }

		public string BuildConnectionString()
		{
			if (String.IsNullOrEmpty(this.User) && String.IsNullOrEmpty(this.Password))
			{
				this.UseTrustedConnection = true;
			}

			var builder =
				new SqlConnectionStringBuilder()
				{
					DataSource = this.Server,
					InitialCatalog = this.Database,
					IntegratedSecurity = this.UseTrustedConnection
				};

			if (!this.UseTrustedConnection)
			{
				if (this.User != null)
				{
					builder.UserID = this.User;
				}

				if (this.Password != null)
				{
					builder.Password = this.Password;
				}
			}

			return builder.ConnectionString;
		}
	}
}
